import Container from './template/container';
import Template from './template/template';
import './lib/vant/css/index.css';

class uploadImage extends Container {

  el = null;
  scriptVantElement = null;
  scriptVue3Element = null;
  scriptLoaderElement = null;
  container = null;
  options = {
    url: '',
    limitCount: 0,
    accept: [],
    quality: 0,
    litmitSize: 0,
    queueCount: 0
  };
  completedCallback = null;

  constructor(el, options, completedCallback) {
    super();
    this.initOptions(options);
    this.completedCallback = completedCallback;
    this.el = el;
    this.initEnv();
    this.init();
  }

  initEnv() {
    const scriptVue3Element = document.createElement('script');
    scriptVue3Element.src = './lib/vue/vue.global.prod.js';
    this.scriptVue3Element = scriptVue3Element;
    const scriptVantElement = document.createElement('script');
    scriptVantElement.src = './lib/vant/vant.min.js';
    this.scriptVantElement = scriptVantElement;
    document.head.appendChild(scriptVue3Element);
    document.head.appendChild(scriptVantElement);
  }

  init() {
    this.random();
    this.initVue();
  }

  initOptions(options) {
    const { url, limitCount, accept, quality, litmitSize, queueCount } = options;
    this.options.url = url;
    this.options.accept.length === 0 ? this.options.accept = ['image/*'] : this.options.accept = accept; //defult file accept upload with image/*
    this.options.limitCount = limitCount ?? 5; //defult limit file upload conut is 5
    this.options.quality = quality ?? 1; //defult do not use compress
    this.options.litmitSize = litmitSize ?? 1.5; //defult use compress size 1.5MB
    this.options.queueCount = queueCount ?? 3; //defult queue limit conut is 3
  }

  random() {
    this.el.appendChild(this.uploadContainer());
    this.container = this.el.querySelector('.sky-upload-container');
  }

  initVue() {
    this.scriptVue3Element.onload = () => {
      this.initVant();
    };
  }

  initVant() {
    this.scriptVantElement.onload = () => {
      const { createApp } = Vue;
      const app = createApp();
      app.use(vant);
      app.use(vant.Uploader);
      app.component('upload', Template(Vue, this.options, resultCallback.bind(this)));
      app.mount(this.container);

      function resultCallback(data) {
        if(this.completedCallback) {
          this.completedCallback(data);
        }
      }
    };
  }
}

export default uploadImage;
